<?php
/**
 * Created by PhpStorm.
 * User: hao
 * Date: 2018/10/30
 * Time: 10:52 AM
 */

namespace app\api\controller\v1;


use app\api\controller\BaseController;
use app\api\model\User;
use app\api\service\Token as TokenService;
use app\api\validate\AddressNew;
use app\lib\exception\SuccessMessage;
use app\lib\exception\UserException;

class Address extends BaseController
{
    protected $beforeActionList = [
        'checkPrimaryScope' => ['only' => 'createOrUpdateAddress']
    ];

    public function createOrUpdateAddress() {

        $validate = new AddressNew();
        $validate->goCheck();

        //根据token来获取uid
        //根据uid查询判断用户数据
        //获取用户从客户端提交来的地址信息
        //根据用户地址信息是否存在，判断是变更还是添加

        $uid = TokenService::getCurrentUid();//获取封装的uid，慢慢的仪式感
        $user = User::get($uid);
        if (!$user){
            throw new UserException();
        }
        $dataArray = $validate->getDataByRule(input('post.'));
        $userAddress = $user->address;
        if (!$userAddress) {
            $user->address()->save($dataArray);
        }else {
            $user->address->save($dataArray);//TODO:不太明白~
        }
        return json(new SuccessMessage());
    }
}